/**
 * 页面事件
 * @author luguoxiang
 * @date 2023-12-28
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { onActivated, onBeforeMount, onMounted, onUnmounted } from 'vue';
import { onBeforeRouteLeave, RouteLocationNormalized, useRoute } from 'vue-router';
import { addEventListener, debounce, removeEventListener } from '@/soar';
import router from '@/router';

type Listener = (to: RouteLocationNormalized, form: RouteLocationNormalized) => boolean | void;
const listeners: Listener[] = [];
router.beforeEach((to, from, next) => {
  // @ts-ignore
  const ls = listeners.filter((listener) => listener.path === to.path);
  for (const listener of ls) {
    if (listener(to, from) === false) {
      return;
    }
  }
  next();
});

/**
 * 当路由进入页面前
 * @param listener
 */
export function onBeforeRouteEnter(listener: Listener) {
  // @ts-ignore
  listener.path = useRoute().path;
  onUnmounted(() => {
    // @ts-ignore
    const index = listeners.indexOf(listener);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  });
  onBeforeMount(() => {
    // @ts-ignore
    const index = listeners.indexOf(listener);
    if (index === -1) {
      // @ts-ignore
      listeners.push(listener);
    }
  });
}

// /**
//  * 路由进入时触发，路由关闭前不会再触发，二级页面返回不会触发
//  */
// export function onLoad(call: (query: any, params: any) => void) {
//   const instance = getCurrentInstance();
//   const route = useRoute();
//   onMounted(() => {
//     call(route.query, route);
//     console.log('onMounted', instance);
//   });
//   onActivated(() => {
//     console.log('onActivated', instance);
//   });
//   onUnmounted(() => {
//     console.log('onUnmounted', instance);
//   });
//   onBeforeRouteUpdate((to, from) => {
//     console.log('onBeforeRouteUpdate', instance);
//   });
//   onBeforeRouteLeave((to, from) => {
//     console.log('onBeforeRouteLeave', instance);
//   });
// }
//
// /**
//  * 页面显示时触发
//  */
// export function onUnload(call: () => void) {
//   onUnmounted(call);
// }

/**
 * 页面显示时触发
 */
export function onShow(call: () => void) {
  const visible = debounce(() => {
    if (document.visibilityState === 'visible') {
      call();
    }
  }, 50);
  onUnmounted(() => {
    removeEventListener(document, 'visibilitychange', visible);
  });
  onMounted(() => {
    visible();
    addEventListener(document, 'visibilitychange', visible);
  });
  onActivated(visible);
}

/**
 * 页面隐藏时触发
 */
export function onHide(call: () => void) {
  call = debounce(call, 50);
  const hidden = () => {
    if (document.visibilityState === 'hidden') {
      call();
    }
  };
  onUnmounted(() => {
    call();
    removeEventListener(document, 'visibilitychange', hidden);
  });
  onMounted(() => {
    addEventListener(document, 'visibilitychange', hidden);
  });
  onBeforeRouteLeave(() => {
    call();
  });
}
